package com.anti.core.aop;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.anti.commom.constant.AopSortConstant;
import com.anti.commom.constant.CommonConstant;
import com.anti.core.context.login.LoginContextHolder;
import com.anti.core.log.LogManager;
import com.anti.commom.annotation.BusinessLog;
import com.anti.modular.sys.auth.pojo.SysLoginUser;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;

/**
 * 业务日志aop切面
 */
@Aspect
@Order(AopSortConstant.BUSINESS_LOG_AOP)
public class BusinessLogAop {

    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.anti.commom.annotation.BusinessLog)")
    public void getLogPointCut() {
    }

    /**
     * 操作成功返回结果记录日志
     * @param joinPoint
     * @param result
     */
    @AfterReturning(value = "getLogPointCut()", returning = "result")
    public void afterReturning(JoinPoint joinPoint, Object result) {
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method method = methodSignature.getMethod();
        BusinessLog businessLog = method.getAnnotation(BusinessLog.class);
        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUserWithoutException();
        String account = CommonConstant.UNKNOWN;
        if(ObjectUtil.isNotNull(sysLoginUser)) {
            account = sysLoginUser.getAccount();
        }
        //异步记录日志
        LogManager.me().executeOperationLog(businessLog, account, joinPoint, JSON.toJSONString(result));
    }

//    /**
//     * 操作发生异常记录日志
//     */
//    @AfterThrowing(pointcut = "getLogPointCut()", throwing = "exception")
//    public void doAfterThrowing(JoinPoint joinPoint, Exception exception) {
//        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
//        Method method = methodSignature.getMethod();
//        BusinessLog businessLog = method.getAnnotation(BusinessLog.class);
//        SysLoginUser sysLoginUser = LoginContextHolder.me().getSysLoginUserWithoutException();
//        String account = CommonConstant.UNKNOWN;
//        if(ObjectUtil.isNotNull(sysLoginUser)) {
//            account = sysLoginUser.getAccount();
//        }
//        //异步记录日志
//        LogManager.me().executeExceptionLog(businessLog, account, joinPoint, exception);
//    }
}
